package com.cn.jwt.zy.jwt.filter;

import com.cn.jwt.zy.jwt.config.JwtHelpr;
import com.cn.jwt.zy.jwt.controller.rquest.UserReq;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.Base64Utils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt登录过滤
 *
 * @author zhangyi
 * @date 2018/12/15 17:46
 */
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter{

    private AuthenticationManager authenticationManager;

    public JwtLoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    /**
     * 自定义验证规则
     *
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        System.out.println("验证用户名和密码是否正确");
        //模拟用户名和密码
        UserReq userReq = new UserReq("admin","123");
        //构建用户信息
        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        userReq.getUserName(),
                        userReq.getPassword()));

    }

    /**
     * 成功验证
     *
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {
        UserReq user = (UserReq) authResult.getPrincipal();
        //获取jwt生成的token
        String token = JwtHelpr.createJwt(user.getUserName(),
                user.getPassword(),
                "1",
                30,
                Base64Utils.encode("123".getBytes()).toString());
        //请求时携带此认证头
        response.addHeader("Authorization",token);
        System.out.println("验证成功");
    }
}
